"""CopyRight WangShiheng(C) and ChengPeishuo(C)"""
__config__ = {
    'Open source licenses': 'GPL4.0',
    'author': ['WangShiheng', 'ChengPeishuo'],
    'VerSion': '1.0.1'
}

import json
import os
import time
from sys import stdout
from tkinter import *
from tkinter import ttk
from urllib.request import urlretrieve
import api_read
import requests


class GUI:
    def __init__(self, class_Tk_object):
        self.init_window_name = class_Tk_object

    def init_gui(self):
        '''设置最初始GUI'''
        self.init_window_name.title(f"爬取QQ音乐 v{__config__['VerSion']}")  # 290 160为窗口大小，+10 +10 定义窗口弹出时的默认展示位置
        self.init_window_name.geometry('1068x681+10+10')  # 窗口背景色，其他背景色见：blog.csdn.net/chl0000/article/details/7657887
        self.init_window_name.attributes("-alpha", 0.9)  # 虚化，值越小虚化程度越高
        # 标签
        self.init_message_label = Label(self.init_window_name, text="歌曲名")
        self.init_message_label.grid(row=0,column=0)
        # 文本框
        self.init_data_Text = Text(self.init_window_name, width=60, height=5)  # 原始数据录入框
        self.init_data_Text.grid(row=1,column=0)
        self.button_get_text = Button(self.init_window_name, text='开始爬取', bg='pink', width=10, command=self._get_text)
        self.button_get_text.grid(row=2,column=0)
        # 表格
        self.treeview = ttk.Treeview()

    def _get_text(self):
        '''获取歌曲名称并进入'''
        message = self.init_data_Text.get(1.0, END)
        self.showTree(GetSongList(message))

    def showTree(self, datas):
        '''展示表单并选择下载歌曲'''
        # 表单
        data = datas[0]
        self.treeview["columns"] = ("歌名", "歌手名")  # #定义列
        self.treeview.column("歌名", width=100)  # #设置列
        self.treeview.column("歌手名", width=100)
        self.treeview.heading("歌名", text="歌名")  # #设置显示的表头名
        self.treeview.heading("歌手名", text="歌手")
        for dan in range(len(data)):
            da = data[dan]
            self.treeview.insert("", dan, text=da[0], values=(da[1], da[2]))
        
        # 标签
        self.treeviewPS = Label(self.init_window_name, text="请选中想要爬取的歌曲：")
        self.treeviewPS.grid(row=3,column=0)
        self.treeview.grid(row=4,column=0)
        # 按钮
        self.main2button = Button(self.init_window_name, text='开始爬取', bg='pink', width=10,
                                  command=lambda: GetSongFile(datas[1], datas[2],self.treeview.item(self.treeview.focus())['text']))  # lambda: GetSongFile(datas[1], datas[2], myint(self.treeview.focus()))
        self.main2button.grid(row=5,column=0)


def Time_1():
    '''进度条'''
    for i in range(1, 51):
        stdout.write('\r')
        stdout.write('{0}% |{1}'.format(int(i % 51) * 2, int(i % 51) * '■'))
        stdout.flush()
        time.sleep(0.125)
    stdout.write('\n')


def GetSongList(w):
    '''获取歌曲列表'''
    url = 'https://c.y.qq.com/soso/fcgi-bin/client_search_cp'
    parses = {'ct': 24, 'qqmusic_ver': 1298, 'new_json': 1, 'remoteplace': 'txt.yqq.song',
              'searchid': 63229658163010696,
              't': 0, 'aggr': 1, 'cr': 1, 'catZhida': 1, 'lossless': 0, 'flag_qc': 0, 'p': 1, 'n': 10, 'w': w,
              'g_tk': 5381,
              'loginUin': 0, 'hostUin': 0, 'format': 'json', 'inCharset': 'utf8', 'outCharset': 'utf-8', 'notice': 0,
              'platform': 'yqq.json', 'needNewCode': 0}

    content = requests.get(url=url, params=parses)
    str_1 = content.text

    dict_1 = json.loads(str_1)

    song_list = dict_1['data']['song']['list']

    str_3 = '''https://u.y.qq.com/cgi-bin/musicu.fcg?-=getplaysongvkey5559460738919986&g_tk=5381&loginUin=0&hostUin=0
    &format=json&inCharset=utf8&outCharset=utf-8&notice=0&platform=yqq.json&needNewCode=0&data={"req":{
    "module":"CDN.SrfCdnDispatchServer","method":"GetCdnDispatch","param":{"guid":"1825194589","calltype":0,
    "userip":""}},"req_0":{"module":"vkey.GetVkeyServer","method":"CgiGetVkey","param":{"guid":"1825194589",
    "songmid":["%s"],"songtype":[0],"uin":"0","loginflag":1,"platform":"20"}},"comm":{"uin":0,"format":"json",
    "ct":24,"cv":0}} '''

    url_list = []
    music_name = []
    cfglist = []
    for i in range(len(song_list)):
        singerName = []
        for singer in song_list[i]['singer']:
            singerName.append(singer['name'])
        music_name.append(song_list[i]['name'] + '-' + str(singerName)[1:-1])

        cfglist.append([i + 1, song_list[i]['name'], singerName])
        url_list.append(str_3 % (song_list[i]['mid']))
    return cfglist, music_name, url_list


def GetSongFile(music_name, url_list, id):
    '''下载歌曲'''
    print(id-1)
    content_json = requests.get(url=url_list[id - 1])

    dict_2 = json.loads(content_json.text)

    url_ip = dict_2['req']['data']['freeflowsip'][1]

    purl = dict_2['req_0']['data']['midurlinfo'][0]['purl']

    downlad = url_ip + purl
    print(downlad)
    try:
        os.mkdir('./QQ音乐')
    except Exception:
        pass

    finally:
        try:
            print('开始下载...')
            urlretrieve(url=downlad, filename='./QQ音乐/{}.mp3'.format(music_name[id - 1]))
            Time_1()
            print('{}.mp3下载完成！'.format(music_name[id - 1]))
        except Exception as e:
            print(e, '对不起，你没有该歌曲的版权！')


if __name__ == '__main__':
    apidict = api_read.start()
    try:
        parms = GetSongList(apidict['w'])
        GetSongFile(parms[1],parms[2],1)
    except:
        tk = Tk()
        gui = GUI(tk)
        gui.init_gui()
        tk.mainloop()
